package com.nowcoder.community.controller;

import com.google.code.kaptcha.Producer;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.utils.CommonUtil;
import com.nowcoder.community.utils.ConstantUtil;
import com.nowcoder.community.utils.RedisKeyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: shuhuang
 * @description: 登录和注册业务处理
 * @Date: 2022/10/6 20:22
 * @Version java version 1.8
 */
@Controller
public class LoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private Producer kaptchaProducer;
    @Value("${server.servlet.context-path}")
    private String contextPath;
    @Autowired
    private RedisTemplate redisTemplate;

    private static final Logger logger = LoggerFactory.getLogger("ERROR_LOGGER");

    @GetMapping(path = "/register")
    public String getRegisterPage() {
        return "/site/register";
    }

    @GetMapping(path = "/login")
    public String getLoginPage() {
        return "/site/login";
    }

    /**
     * 接受前端传递过来的数据，处理注册页信息
     *
     * @param model
     * @param user
     * @return
     */
    @PostMapping(path = "/register")
    public String postRegister(Model model, User user) {
        Map<String, Object> registerMap = userService.register(user);
        if (registerMap == null || registerMap.isEmpty()) {
            registerMap.put("msg", "注册成功，我们已向您的邮箱发送了一封激活账号的邮件，请您尽快激活！");
            registerMap.put("target", "/index");
            model.addAllAttributes(registerMap);
            return "/site/operate-result";
        }
        model.addAllAttributes(registerMap);
        return "/site/register";
    }

    /**
     * 用来激活用户注册的账号
     */
    @GetMapping(path = "/activation/{userId}/{code}")
    public String getActive(@PathVariable("userId") int userId, @PathVariable("code") String code, Model model) {
        int activation = userService.activation(userId, code);
        if (activation == ConstantUtil.ACTIVATION_SUCCESS) {
            model.addAttribute("msg", "激活成功，您的账号已经可以正常使用了！");
            model.addAttribute("target", "/login");
        } else if (activation == ConstantUtil.ACTIVATION_REPEAT) {
            model.addAttribute("msg", "无效操作，该账号已经被激活过了！");
            model.addAttribute("target", "/index");
        } else {
            model.addAttribute("msg", "激活失败，您提供的激活码不正确！");
            model.addAttribute("target", "/index");
        }
        return "/site/operate-result";
    }

    /**
     * 向浏览器写入生成的验证码
     */
    @GetMapping(path = "/kaptcha")
    public void getKaptcha(HttpServletResponse response) {
        //生成验证码
        String text = kaptchaProducer.createText();
        BufferedImage image = kaptchaProducer.createImage(text);
        //验证码的归属
        String kapatchaOwner = CommonUtil.generateUUID();
        Cookie cookie = new Cookie("kapatchaOwner", kapatchaOwner);
        cookie.setMaxAge(60);
        cookie.setPath(contextPath);
        response.addCookie(cookie);

        //将验证码存入redis
        String kaptchaKey = RedisKeyUtil.getKaptchaKey(kapatchaOwner);
        redisTemplate.opsForValue().set(kaptchaKey, text, 60, TimeUnit.SECONDS);

        //将图片输出给浏览器
        response.setContentType("image/png");
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            ImageIO.write(image, "png", outputStream);
        } catch (IOException e) {
            logger.error("响应验证码失败！" + e.getMessage());
        }
    }

    /**
     * 接受前端传递过来的数据，处理登录页信息
     */
    @PostMapping(path = "/login")
    public String login(Model model, String username, String password, String code,
                        boolean rememberme, HttpServletResponse response,
                        @CookieValue(value = "kapatchaOwner", required = false) String kapatchaOwner) {
        //检查验证码
        String kaptcha = null;
        if (StringUtils.hasText(kapatchaOwner)) {
            String kaptchaKey = RedisKeyUtil.getKaptchaKey(kapatchaOwner);
            kaptcha = (String) redisTemplate.opsForValue().get(kaptchaKey);
        }
        if (!StringUtils.hasText(kaptcha) || !StringUtils.hasText(code) || !kaptcha.equalsIgnoreCase(code)) {
            model.addAttribute("codeMsg", "验证码不正确");
            return "/site/login";
        }
        //检查账号密码
        int expiredSeconds = rememberme ? ConstantUtil.REMEMBER_EXPIRED_SECONDS : ConstantUtil.DEFAULT_EXPIRED_SECONDS;
        Map<String, Object> map = userService.login(username, password, expiredSeconds);
        if (map.containsKey("ticket")) {
            Cookie cookie = new Cookie("ticket", map.get("ticket").toString());
            cookie.setMaxAge(expiredSeconds);
            cookie.setPath(contextPath);
            response.addCookie(cookie);
            return "redirect:/index";
        } else {
            model.addAllAttributes(map);
            return "/site/login";
        }
    }

    /**
     * 退出登录
     *
     * @param ticket
     * @return
     */
    @GetMapping(path = "/logout")
    public String logout(@CookieValue("ticket") String ticket) {
        userService.logout(ticket);
        SecurityContextHolder.clearContext();
        return "redirect:/login";
    }
}
